
/**
 * 放音乐和音效的
 */
class Tracker {

  initSeVolume = 0;
  initAudioVolume = 0;
  // 背景音乐是否需要播放, 不受音量影响
  needPlay = false;

  constructor(params, audioVolume = 0.5, seVolume = 0.4) {
    const { assetPath } = params;
    this.sound = params.sound;

    this.initAudioVolume = audioVolume;
    this.initSeVolume = seVolume;
    this.themeAudio = null;
    this.se = null;

    const { sounds } = this.sound;
    sounds.load([
      assetPath('show/MM3StageSelectSE.m4a'),
      assetPath('show/2A03-MM3StageSelect.m4a')
    ]);

    // 音效部分
    sounds.whenLoaded = () => {
      // se
      this.se = sounds[assetPath('show/MM3StageSelectSE.m4a')];
      this.se.volume = this.initSeVolume;

      // themeAudio
      this.themeAudio = sounds[assetPath('show/2A03-MM3StageSelect.m4a')];
      this.themeAudio.volume = this.initAudioVolume;
      this.themeAudio.loop = true;
    }
  }

  /**
   * 音乐
   * @param {number} audioVolume 
   */
  setVolume (audioVolume) {
    if (!this.themeAudio) {
      this.initAudioVolume = audioVolume;
      return;
    }

    const { themeAudio } = this;
    const oldVolume = themeAudio.volume;
    themeAudio.volume = audioVolume;
    if (this.needPlay) {
      if (themeAudio.volume > 0) {
        if (oldVolume === 0) {
          themeAudio.playFrom(0);
        }
      } else {
        themeAudio.pause();
      }
    }
  }

  getAudioVolume () {
    return this.themeAudio ? this.themeAudio.volume : this.initAudioVolume;
  }

  setSeVolume (seVolume) {
    if (this.se) {
      this.se.volume = seVolume;
    } else {
      this.initSeVolume = seVolume;
    }
  }

  getSeVolume () {
    return (this.se) ? this.se.volume : this.initSeVolume;
  }

  play () {
    this.needPlay = true;
    if (!this.themeAudio) {
      return;
    }
    const { themeAudio } = this;

    if (themeAudio.volume === 0) {
      return;
    }
    if (!themeAudio.playing) {
      // 重置播放位置到开头
      themeAudio.playFrom(0);
    }
  }

  pause () {
    this.needPlay = false;
    const { themeAudio } = this;
    themeAudio.pause();
  }

  playSe () {
    if (!this.se) { return; }
    const { se } = this;

    if (se.volume === 0) {
      return;
    }
    // 同一时间只播放一个音效
    se.playFrom(0);
  }
}

export {
  Tracker
};
